<?php

require_once __DIR__.'/vendor/autoload.php';

// 加载环境变量
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// 创建数据库连接
try {
    $pdo = new PDO(
        "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']};charset=utf8mb4",
        $_ENV['DB_USERNAME'],
        $_ENV['DB_PASSWORD'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

    echo "✅ 数据库连接成功\n";

    // 检查并获取超级管理员角色ID
    $superAdminResult = $pdo->query("SELECT id FROM roles WHERE code = 'super_admin'");
    $superAdminRole = $superAdminResult->fetch();

    if (!$superAdminRole) {
        echo "❌ 未找到超级管理员角色\n";
        exit(1);
    }

    $superAdminId = $superAdminRole['id'];
    echo "✅ 找到超级管理员角色 ID: {$superAdminId}\n";

    // 为admin用户分配超级管理员角色
    $userResult = $pdo->query("SELECT id FROM users WHERE username = 'admin'");
    $user = $userResult->fetch();

    if ($user) {
        $stmt = $pdo->prepare("
            INSERT INTO user_roles (user_id, role_id, created_at, updated_at)
            VALUES (?, ?, NOW(), NOW())
        ");
        $stmt->execute([$user['id'], $superAdminId]);
        echo "✅ 为用户 'admin' 分配超级管理员角色\n";
    }

    // 现在为超级管理员分配所有功能权限
    echo "🔐 为超级管理员分配权限...\n";
    $functionsResult = $pdo->query("SELECT id, code FROM functions");
    $functions = $functionsResult->fetchAll();

    $stmt = $pdo->prepare("
        INSERT INTO role_function_permissions
        (role_id, function_id, auto_granted, granted_by, granted_at, created_at, updated_at)
        VALUES (?, ?, 1, 1, NOW(), NOW(), NOW())
    ");

    foreach ($functions as $function) {
        $stmt->execute([$superAdminId, $function['id']]);
        echo "✅ 分配权限: {$function['code']}\n";
    }

    echo "\n🎉 角色和权限设置完成！\n";

    // 验证结果
    $roleCountResult = $pdo->query("SELECT COUNT(*) as count FROM roles");
    $roleCount = $roleCountResult->fetch()['count'];

    $permissionCountResult = $pdo->query("SELECT COUNT(*) as count FROM role_function_permissions WHERE role_id = {$superAdminId}");
    $permissionCount = $permissionCountResult->fetch()['count'];

    echo "📊 创建了 {$roleCount} 个角色\n";
    echo "📊 超级管理员拥有 {$permissionCount} 个权限\n";

} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
}
